﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Shop.Base.Entity;
using Shop.Base.Entity.Insert;
using Shop.Base.Entity.Select;
using Shop.Base.Entity.Update;
using Shop.Base.Interface;
using Shop.Entity;
using Shop.Tools;
using Shop.Web.Filter;
using Shop.Web.Models;

namespace Shop.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class SystemUserController : Controller
    {
        private IMapper mapper;
        private ISystemUser user;
        private ISystemUserRole userRole;
        private ISystemRole role;

        public SystemUserController(IMapper mapper, ISystemUser _user, ISystemUserRole _userRole,ISystemRole _role)
        {
            this.mapper = mapper;
            this.user = _user;
            this.userRole = _userRole;
            this.role = _role;
        }
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public IActionResult GetList(string name, string englishName, string account, int isLogin = -1, int isNormal = -1, int isDel = -1, int pageIndex = 1, int pageSize = 15)
        {
            try
            {
                var list = user.GetPage(name, englishName, account, isLogin, isNormal, isDel, pageIndex, pageSize, out int total);
                var showList = mapper.Map<List<SystemUserPo>, List<ShowSystemUser>>(list);
                return Json(new ResultModel
                {
                    code = OperationResultType.GetList,
                    data = new { list = showList, total },
                    error_msg = "",
                    success = true
                });
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                return Json(new ResultModel { code = OperationResultType.Throws, data = new List<string>(), error_msg = "查询异常", success = false });
            }
        }

        public IActionResult Edit(Guid? userId)
        {
            var comUser = HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
            if (userId.HasValue && !userId.Value.IsEmptyGuid())
            {
                var users = user.Find<SystemUserPo>(userId.Value);
                ViewBag.model = users.ToJsonData();
            }
            else
            {
                ViewBag.model = new AddSystemUser { IsLogin = true, CreateId = comUser.Id, CreateName = comUser.UserName, Passwd = "" }.ToJsonData();
            }
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit([FromForm]SystemUserPo model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var comUser = HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
                    if (model.Id.IsEmptyGuid())
                    {
                        var pwds = Tools.Util.Tools.MD5Encrypt(model.Passwd);
                        model.Passwd = pwds;
                        var inserts = mapper.Map<SystemUserPo, AddSystemUser>(model);
                        user.Insert(inserts, comUser);
                    }
                    else
                    {
                        var updates = mapper.Map<SystemUserPo, UpdateSystemUser>(model);
                        user.Update(updates, comUser);
                    }
                    return RedirectToAction("Index");
                }
                ViewBag.model = model.ToJsonData();
                TempData["errMsg"] = new JsMessage("无效的操作", 5, JsMessageType.Warning).ToString();
                return View();
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                ViewBag.model = model.ToJsonData();
                if (e.Message.Contains("#"))
                    TempData["errMsg"] = new JsMessage(e.Message.Replace("#",""), 5, JsMessageType.Warning).ToString();
                else
                    TempData["errMsg"] = new JsMessage("保存出现异常", 5, JsMessageType.Danger).ToString();
                return View();
            }
        }

        [HttpPost]
        public IActionResult Delete(Guid id)
        {
            try
            {
                if (id.IsEmptyGuid()) return Json(new ResultModel { code = OperationResultType.ParamError, error_msg = "指定删除的用户不存在", success = false });
                var comUser = HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
                user.Delete<UpdateSystemUser>(id, comUser);
                return Json(new ResultModel { code = OperationResultType.Success, error_msg = "删除成功", success = true });
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                return Json(new ResultModel { code = OperationResultType.Throws, error_msg = "系统异常，请刷新再试", success = false });
            }
        }

        //设置用户角色
        public IActionResult SetRole(Guid userId)
        {
            if (userId.IsEmptyGuid()) return RedirectToAction("Index");
            ViewBag.AllRole = role.GetAll<SystemRolePo>().Select(x=> new{key=x.Id,label=x.RoleName }).ToJsonData();
            ViewBag.userId = userId;
            ViewBag.selectedRole = userRole.GetList(userId).Select(x => x.RoleId).ToJsonData();
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult SetRole(List<Guid> list, Guid userId)
        {
            ViewBag.AllRole = role.GetAll<SystemRolePo>().Select(x => new { key = x.Id, label = x.RoleName }).ToJsonData();
            ViewBag.userId = userId;
            ViewBag.selectedRole = list.ToJsonData();
            try
            {
                if (ModelState.IsValid)
                {
                    userRole.MultSave(list.Where(x => !x.IsEmptyGuid()).Select(x => new SystemUserRolePo { RoleId = x, UserId = userId }).ToList(), userId);
                    return RedirectToAction("Index");
                }
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                if (e.Message.Contains("#"))
                    TempData["errMsg"] = new JsMessage(e.Message.Replace("#", ""), 5, JsMessageType.Warning).ToString();
                else
                    TempData["errMsg"] = new JsMessage("保存出现异常", 5, JsMessageType.Danger).ToString();
            }
            return View();
        }

        [HttpPost]
        public IActionResult InitPwd(Guid userId)
        {
            try
            {
                if (userId.IsEmptyGuid()) return Json(new ResultModel { code = OperationResultType.ParamError, error_msg = "指定需要初始化密码的用户不存在", success = false });
                var comUser = HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
                var issucc=user.InitPasswd(userId,Tools.Util.Tools.MD5Encrypt(Tools.GlobalConst.InitPassword), comUser);
                return Json(new ResultModel { code = issucc?OperationResultType.Success:OperationResultType.Error, error_msg = issucc?"初始化成功":"初始化失败", success = true });
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                return Json(new ResultModel { code = OperationResultType.Throws, error_msg = "系统异常，请刷新再试", success = false });
            }
        }

        //修改密码
        [SignNoPower]
        public IActionResult ChangePasswd()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [SignNoPower]
        public IActionResult ChangePasswd(string oldPasswd, string newPasswd, string confirmPasswd)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (!oldPasswd.IsNullOrEmpty() && !newPasswd.IsNullOrEmpty() && !confirmPasswd.IsNullOrEmpty()&&newPasswd==confirmPasswd)
                    {
                        var comUser = HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
                        var users=user.Find<SystemUserPo>(comUser.Id);
                        if(users.IsDel)throw new Exception("#账号不存在");
                        if(users.Passwd!=Tools.Util.Tools.MD5Encrypt(oldPasswd)) throw new Exception("#旧密码错误"); 
                        users.Passwd= Tools.Util.Tools.MD5Encrypt(newPasswd) ;
                        users.UpdateId = comUser.Id;
                        users.UpdateAt=DateTime.Now;
                        users.UpdateName = comUser.UserName;
                        user.ChangePassword(users);
                        return RedirectToAction("Index", "Default");
                    }
                    if(oldPasswd.IsNullOrEmpty()) throw new Exception("#旧密码不存在");
                    if(newPasswd.IsNullOrEmpty()) throw new Exception("#新密码不存在");
                    if(confirmPasswd.IsNullOrEmpty()) throw new Exception("#确认密码不存在");
                    if(newPasswd!=confirmPasswd) throw new Exception("#新密码与确认密码不一致");
                }
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                if (e.Message.Contains("#"))
                    TempData["errMsg"] = new JsMessage(e.Message.Replace("#", ""), 5, JsMessageType.Warning).ToString();
                else
                    TempData["errMsg"] = new JsMessage("保存出现异常", 5, JsMessageType.Danger).ToString();
            }

            return View();
        }
    }
}